package com.xiaoshuidi.cloud.module.member.service.topics;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.redis.lock.DistributeLock;
import com.xiaoshuidi.cloud.module.member.constant.Constant;
import com.xiaoshuidi.cloud.module.member.controller.admin.topics.vo.MemberTopicsPostListVo;
import com.xiaoshuidi.cloud.module.member.controller.admin.topics.vo.TopicsPostDetailVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.topics.vo.TopicsPostPageVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.topics.vo.TopicsPostUpdateStateVO;
import com.xiaoshuidi.cloud.module.member.controller.app.topics.vo.AddLikeVo;
import com.xiaoshuidi.cloud.module.member.controller.app.topics.vo.AppTopicsPostPageVO;
import com.xiaoshuidi.cloud.module.member.controller.app.topics.vo.MemberTopicsPostCreateVO;
import com.xiaoshuidi.cloud.module.member.mapper.topics.MemberTopicsPostMapper;
import com.xiaoshuidi.cloud.module.member.mapper.topics.MemberTopicsThumbsRecordMapper;
import com.xiaoshuidi.cloud.module.member.pojo.topics.MemberTopics;
import com.xiaoshuidi.cloud.module.member.pojo.topics.MemberTopicsPost;
import com.xiaoshuidi.cloud.module.member.pojo.topics.MemberTopicsThumbsRecord;
import com.xiaoshuidi.cloud.module.member.repository.MemberTopicsPostRepository;
import com.xiaoshuidi.cloud.module.member.repository.MemberTopicsRepository;
import com.xiaoshuidi.cloud.module.member.repository.MemberTopicsThumbsRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberTopicsPostServiceImpl extends ServiceImpl<MemberTopicsPostMapper, MemberTopicsPost> implements MemberTopicsPostService {

    private final MemberTopicsPostRepository memberTopicsPostRepository;
    private final MemberTopicsThumbsRecordRepository memberTopicsThumbsRecordRepository;
    public static final String ADD_LIKE = "topic:add:like";//点赞

    private final MemberTopicsRepository memberTopicsRepository;

    @Override
    public Boolean create(MemberTopicsPostCreateVO createReqVO) {
        memberTopicsPostRepository.create(createReqVO);
        return true;
    }

    @Override
    public PageResult<MemberTopicsPostListVo> getPage(TopicsPostPageVO pageVO) {
        IPage<MemberTopicsPostListVo> page = memberTopicsPostRepository.getPage(pageVO);
        PageResult<MemberTopicsPostListVo> pageResult = PageResult.empty();
        pageResult.setList(page.getRecords());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Override
    public TopicsPostDetailVO getById(Long id) {
        MemberTopicsPost byId = memberTopicsPostRepository.getById(id);
        TopicsPostDetailVO vo = new TopicsPostDetailVO();
        BeanUtils.copyProperties(byId, vo);
        return vo;
    }

    @Override
    public Boolean updateStatus(TopicsPostUpdateStateVO updateStateVO) {
        memberTopicsPostRepository.updateStatus(updateStateVO);
        return true;
    }

    @Override
    public PageResult<TopicsPostDetailVO> getAppPage(AppTopicsPostPageVO pageVO) {
        IPage<TopicsPostDetailVO> page = memberTopicsPostRepository.getAppPage(pageVO);
        List<TopicsPostDetailVO> records = page.getRecords();
        records = records.stream().peek(r -> {
//            if (ObjectUtils.isNotEmpty(r.getRecordId())) {
//                //如果是个人中心里的点赞
//                if (ObjectUtils.isNotEmpty(pageVO.getUserId())) {
//                    r.setFlag(false);
//                } else if (ObjectUtils.isNotEmpty(pageVO.getCreator())) {
//                    //查询所有话题列表，如果用户id等于pageVO.getCreator() 说明不能点赞
//                    if (ObjectUtils.isNotEmpty(r.getUserId()) && r.getUserId().intValue() == pageVO.getCreator().intValue()) {
//                        r.setFlag(false);
//                    } else {
//                        r.setFlag(true);
//                    }
//                }
//            } else {
//                r.setFlag(true);
//            }

            //如果userIds为空则可以点赞
            if (StringUtils.isEmpty(r.getUserIds())) {
                r.setFlag(true);
            } else {
                if (ObjectUtils.isNotEmpty(pageVO.getUserId()) && r.getUserIds().contains(pageVO.getUserId().toString())) {
                    r.setFlag(false);
                } else if (StringUtils.isNotEmpty(pageVO.getCreator()) && r.getUserIds().contains(pageVO.getCreator())) {
                    r.setFlag(false);
                } else {
                    r.setFlag(true);
                }
            }
            //设置生效状态
            MemberTopics t = new MemberTopics();
            t.setEffectBeginTime(r.getEffectBeginTime());
            t.setEffectEndTime(r.getEffectEndTime());
            Integer topicStatus = memberTopicsRepository.getTopicStatus(t);
            r.setTopicStatus(topicStatus);
        }).collect(Collectors.toList());
        PageResult<TopicsPostDetailVO> pageResult = PageResult.empty();
        pageResult.setTotal(page.getTotal());
        pageResult.setList(records);
        return pageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addLike(AddLikeVo vo) {
        String key = ADD_LIKE.concat(vo.getUserId().toString());
        try (DistributeLock lock = DistributeLock.getLock(key)) {
            if (lock.tryLock()) {
                boolean flag = memberTopicsThumbsRecordRepository.alreadyAddLike(vo);
                if (flag) {
                    MemberTopicsThumbsRecord entity = new MemberTopicsThumbsRecord();
                    entity.setTopicPostId(vo.getTopicPostId());
                    entity.setUserId(vo.getUserId());
                    memberTopicsThumbsRecordRepository.save(entity);
                    memberTopicsPostRepository.addLike(vo.getTopicPostId());
                }
            }
        }
        return true;

    }

    @Override
    public List<MemberTopicsPostListVo> exportTopicsPostList(TopicsPostPageVO form) {
        return memberTopicsPostRepository.exportTopicsPostList(form);
    }

    @Override
    public void updateUserId(Long oldUserId, Long userId) {
        this.baseMapper.updateUserId(oldUserId, userId);
        memberTopicsThumbsRecordRepository.updateUserId(oldUserId, userId);
    }
}
